package lol.clann.minecraft.springboot.plugin.core.database.mybatis;

import lol.clann.minecraft.springboot.api.context.PluginContext;
import lol.clann.minecraft.springboot.api.context.SpringContext;
import lol.clann.minecraft.springboot.api.model.core.Plugin;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.mapper.ClassPathMapperScanner;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 如果有数据源
 * 就会启用mybatis
 * xml mapper放在 包路径下任意mapper目录内
 * java mapper放在包路径下任意mapper包内
 *
 * @author pyz
 * @date 2019/4/15 4:57 PM
 */
@Slf4j
@Configuration
@ConditionalOnBean(DataSource.class)
public class ImportMybatis implements BeanDefinitionRegistryPostProcessor {

    /**
     * 注册mapper
     *
     * @param registry
     * @throws BeansException
     */
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
        scanner.setResourceLoader(SpringContext.getSpringApplication().getResourceLoader());
        scanner.setSqlSessionTemplateBeanName("");
        scanner.setSqlSessionFactoryBeanName("sqlSessionFactory");
        scanner.registerFilters();
        for (Plugin plugin : PluginContext.getPlugins()) {
            if (plugin.getBasePackages() == null) {
                continue;
            }
            List<String> basePackages = new ArrayList();
            for (String s : plugin.getBasePackages()) {
                basePackages.add(s + ".**.mapper");
            }
            Set<BeanDefinitionHolder> mappers = scanner.doScan(StringUtils.toStringArray(basePackages));
            for (BeanDefinitionHolder mapper : mappers) {
                LOGGER.info("find java mapper in plugin {}:{}", plugin.getId(), mapper.getBeanDefinition().getBeanClassName());
            }
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }


}
